package app

import (
	"context"
	v1 "k8s.io/api/core/v1"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/log"
	appv1beta1 "taptap.com/app/api/v1beta1"
)

func ReconcileStatus(ctx context.Context, c client.Client, req ctrl.Request) {
	logger := log.FromContext(ctx)
	app := &appv1beta1.App{}
	err := c.Get(ctx, req.NamespacedName, app)
	if err != nil {
		logger.Error(err, "unable to fetch App")
		return
	}

	app.Status.Replicas = app.Spec.Replicas
	endpoints := &v1.Endpoints{
		Subsets: make([]v1.EndpointSubset, 0),
	}
	err = c.Get(ctx, req.NamespacedName, endpoints)
	if err != nil {
		logger.Error(err, "ReconcileStatus failed")
		return
	}

	subSetLength := len(endpoints.Subsets)
	if subSetLength <= 0 {
		return
	}

	app.Status.ReadyReplicas = len(endpoints.Subsets[0].Addresses)
	app.Status.Endpoints = make([]string, 0)
	for _, addr := range endpoints.Subsets[0].Addresses {
		app.Status.Endpoints = append(app.Status.Endpoints, addr.IP)
	}
	err = c.Status().Update(ctx, app)
	if err != nil {
		logger.Error(err, "ReconcileStatus: update app status failed")
	}
}
